import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:http/http.dart' as http;
import 'package:encrypt/encrypt.dart' as encrypt;

class TranslatorError implements Exception {
  final String message;
  TranslatorError(this.message);
  @override
  String toString() => 'TranslatorError: $message';
}

class Iciba {
  final String hostUrl = 'https://www.iciba.com/fy';
  final String apiUrl = 'https://ifanyi.iciba.com/index.php';
  final String signKey = '6dVjYLFyzfkFkk';
  final String encryptKey = 'L4fBtD5fLC9FQw22';
  final String decryptKey = 'aahc3TfyfCEmER33';
  final int inputLimit = 3000;

  String getSign(String queryText) {
    final cryText = '6key_web_new_fanyi$signKey$queryText';
    final sign = md5.convert(utf8.encode(cryText)).toString().substring(0, 16);
    print("sign:${sign}");
    final key = encrypt.Key.fromUtf8(encryptKey);
    final encrypter = encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.ecb));
    final encrypted = encrypter.encrypt(sign, iv: encrypt.IV.fromLength(16));
    return base64.encode(encrypted.bytes);
  }

  Map<String, dynamic> getResult(String content) {
    final key = encrypt.Key.fromUtf8(decryptKey);
    print("key:${key}");
    final encrypter = encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.ecb));
    print("encrypter:${encrypter}");
    final decrypted = encrypter.decrypt64(content, iv: encrypt.IV.fromLength(16));
    print("decrypted:${decrypted}");
    return json.decode(decrypted);
  }

  Future<String> icibaApi(String queryText, {String fromLanguage = 'auto', String toLanguage = 'en'}) async {
    if (queryText.length > inputLimit) {
      throw TranslatorError('Input text too long');
    }
    String sign =  getSign(queryText);
    print("sign:${sign}");
    final params = {
      'c': 'trans',
      'm': 'fy',
      'client': '6',
      'auth_user': 'key_web_new_fanyi',
      'sign': sign,
    };

    final payload = {
      'from': fromLanguage,
      'to': fromLanguage == 'auto' ? 'auto' : toLanguage,
      'q': queryText,
    };

    final uri = Uri.parse(apiUrl).replace(queryParameters: params);
    final response = await http.post(uri, body: payload);

    if (response.statusCode == 200) {
      final data = json.decode(response.body);
      final result = getResult(data['content']);
      return result['out'];
    } else {
      throw TranslatorError('API request failed');
    }
  }
}

// 使用示例
void main() async {
  // 测试 金山翻译
  final iciba = Iciba();
  try {
    final result = await iciba.icibaApi("你好", fromLanguage: "zh", toLanguage: "ka");
    // const content = "nCRjxZwyh/7P3ee74BIU0r+VpYqC1/VewPqzx0un7jyxwY4zP5s7J8rhlkFQVkgZhoViGblBeVZQp56lAt7AZ8HqunXJE5xb4EQg7UPDGFIIHbwZZUDnKQ5V8r9/+guFaJf9MJpvANQw7285y3YD7L9fWOC9Nn0hsLdDAWJOgm4p45ozDcMrAvaLI5kVnkC5DXmu4lgquGouf1F+k4YFpiEUJ5XHAbshY51gmoeoEXYuobI4eswavxrdxqh0HYSXNLxoz198exBfVyR3fSa2eUGRQWYe1P8xK/dskvuEYXw0RbGM0yYu02AzQ2wHI+0PzR1yzSbJQp1MiZ5Y8eisCt9UjVIme7ZpNyfr3u8U3sg=";
    // final result = await iciba.getSign("你好");
    print(result);
  } catch (e) {
    print(e);
  }
}